package com.duofan.gmall.order.service.impl;

import com.alibaba.fastjson.JSON;
import com.duofan.gmall.order.entity.OrderEntity;
import com.duofan.gmall.order.entity.OrderReturnReasonEntity;
import com.duofan.gmall.order.service.OrderReturnReasonService;
import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.core.MessageProperties;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Map;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.duofan.gmall.common.utils.PageUtils;
import com.duofan.gmall.common.utils.Query;

import com.duofan.gmall.order.dao.OrderItemDao;
import com.duofan.gmall.order.entity.OrderItemEntity;
import com.duofan.gmall.order.service.OrderItemService;

//@RabbitListener(queues = {"hello-java-queue"})
@Service("orderItemService")
public class OrderItemServiceImpl extends ServiceImpl<OrderItemDao, OrderItemEntity> implements OrderItemService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<OrderItemEntity> page = this.page(
                new Query<OrderItemEntity>().getPage(params),
                new QueryWrapper<OrderItemEntity>()
        );

        return new PageUtils(page);
    }

    @RabbitHandler
    public void recvMsg(Message msg, OrderReturnReasonEntity content, Channel channel) throws InterruptedException {
        // System.out.println("#recvMsg接收到消息:\n" + JSON.toJSONString(content, true));
        try {
            long deliveryTag = msg.getMessageProperties().getDeliveryTag();
            if(deliveryTag %2 == 0) {
                /**
                 * 签收消息
                 * @Param deliveryTag  由接受者返回
                 * @Param multiple     是否批量确认,否
                 */
                channel.basicAck(deliveryTag, false);
                System.out.println("签收: " + content.getId());
            } else {
                /**
                 * 拒收消息
                 * @Param deliveryTag  由接受者返回
                 * @Param multiple
                 * @Param requeue 为true重新入队,false丢弃
                 */
                channel.basicNack(deliveryTag, false, false);
                System.out.println("拒签: " + content.getId());
            }
            // 没有签收的消息是unack状态
        } catch (IOException e) {
            // 网络中断
            e.printStackTrace();
        }
    }

    @RabbitHandler
    public void recvMsg2(Message msg, OrderEntity content, Channel channel) throws InterruptedException {
        System.out.println("#recvMsg2接收到消息:\n" + JSON.toJSONString(content, true));
    }

}